<template>
	<div class="addBox">
		<div class="addBoxTop">
			<div v-if="detailsId">
				<span class="font_size20">分销规则</span>
			</div>
			<div v-else class="font_size20">分销规则</div>
		</div>
		<div class="addDiv" v-loading="sLoading">
			<div class="profit-box mb20" v-if="objectForm.status == 2 || objectForm.status == 3">
				<el-row :gutter="20">
					<el-col :span="8">
						<el-statistic title="订单总量">
							<template slot="formatter">
								{{ objectForm.num_od }}
							</template>
						</el-statistic>
					</el-col>
					<el-col :span="8">
						<el-statistic title="已分润订单">
							<template slot="formatter">
								{{ objectForm.num_give }}
							</template>
						</el-statistic>
					</el-col>
					<el-col :span="8">
						<el-statistic title="分润金额">
							<template slot="formatter">
								{{ objectForm.total_give }}
							</template>
						</el-statistic>
					</el-col>
				</el-row>
			</div>
			<el-form ref="form" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type">
						<el-option v-for="item in getYunShopsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="'规则名称'" prop="title">
					<el-input v-model="objectForm.title" class="input-w" placeholder="请填写标题, 20个文字内" maxlength="20"
						show-word-limit :disabled="isDisabled || isDisbableInfo.type"></el-input>
				</el-form-item>
				<el-form-item label="分销等级" prop="grade">
					<el-select v-model="objectForm.grade" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type">
						<el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="分润获取类型" prop="ptype">
					<el-select v-model="objectForm.ptype" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type">
						<el-option v-for="item in ptypeList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="'累计金额达到'" prop="v_if">
					<el-input v-model="objectForm.v_if" placeholder="请填写累计金额" :min="0" style="width: 217px;"
						:disabled="isDisabled || isDisbableInfo.type" @input="handlePriceInput"></el-input><span
						class="tip-text">(元)</span>
				</el-form-item>
				<el-form-item :label="'奖励分润金额'" prop="v_give">
					<el-input v-model="objectForm.v_give" placeholder="请填写奖励分润金额" :min="0" style="width: 217px;"
						:disabled="isDisabled || isDisbableInfo.type" @input="handle2PriceInput"></el-input><span
						class="tip-text">(元)</span>
				</el-form-item>
				<el-form-item label="备注" prop="txt">
					<el-input type="textarea" v-model="objectForm.txt" class="input-w" placeholder="请填写备注"
						show-word-limit :disabled="isDisabled || isDisbableInfo.type"></el-input>
				</el-form-item>
				<el-form-item label="启用" prop="value1">
					<div class="switchDiv">
						<el-switch v-model="objectForm.value1"
							:disabled="isDisabled || isDisbableInfo.type"></el-switch>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="addDivBtn">
			<div class="acvite-btn" v-if="objectForm.status == 2" @click="stopActivity">停止</div>
			<!-- objectForm.act == 'add' -->
			<div class="acvite-btn" v-else-if="btnShow" @click="createActivity">提交</div>
			<div class="back-btn" @click="goBack" v-if="isDisbableInfo.index_key == '-1'">返回</div>
		</div>
		<!-- 时间列表 -->
		<timeList @pushtimeData="pushtimeData" ref="timeList"></timeList>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, defineExpose } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import timeList from "@/components/marketingMenu/timeList.vue"
import uploadPic from "@/js/upload/UploadPic.js"
import staticConst from "@/js/const/StaticConst.js"
import { priceInput } from '@/utils/common.js'
import { gradeList, ptypeList } from '@/utils/dict.js'

// 获取当前组件实例
const { proxy } = getCurrentInstance()

const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => [],
	},
	detailID: {
		type: String,
		default: "",
	},
	// 如果是编辑页面，设置某些值不能编辑
	isDisbableInfo: {
		type: Object,
		default: () => ({
			type: false,
		}),
	},
})

const emit = defineEmits(['addTpBmFun'])
// Refs
const form = ref(null)
const sLoading = ref(false)

// State
const objectForm = ref({
	act: "add",
	id: "",
	shopid_yd: "",
	title: "", // 规则名称
	grade: "", // 级别1,2
	ptype: "", // 奖励类型 1按单笔订单金额 2按订单累计金额 3按订单累计数量 4按邀请人数
	v_if: "", // 奖励条件值
	v_give: "", // 奖励金额
	txt: "", // 备注
	status: '', // 启用
	value1: true, // 启用
})

const btnShow = computed(() => {
	return objectForm.value.status == 1 || (props.isDisbableInfo.index_key == '-1' && objectForm.act == 'add') || (props.isDisbableInfo.index_key != '3')
})

const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	title: [
		{ required: true, message: '请填写标题', trigger: 'blur' }
	],
	grade: [
		{ required: true, message: '请选择分销等级', trigger: 'change' }
	],
	ptype: [
		{ required: true, message: '请选择分润获取类型', trigger: 'change' }
	],
	v_if: [
		{ required: true, message: '请填写累计金额', trigger: 'blur' }
	],
	v_give: [
		{ required: true, message: '请填写奖励分润金额', trigger: 'blur' }
	],
})

const getYunShopsList = computed(() => {
	return props.getYunShopList
})

const restFun = () => {
	objectForm.value.id = ""
	detailsId.value = ''
	form.value?.resetFields()
	objectForm.value.act = 'add'
}

const submitForm = async (formName) => {
	console.log("objectForm.value=", objectForm.value)
	const valid = await form.value?.validate()
	if (valid) {
		const params = {
			...objectForm.value,
			status: objectForm.value.value1 ? 2 : 1,
		}
		const res = await proxy.$api({ url: config.yx_ds_event_save, data: params })
		if (res.status == 1) {
			proxy.$message.success(res?.msg || '操作成功')
			emit("addTpBmFun", {
				type: objectForm.value.act,
				status: objectForm.value.value1 ? 2 : 1,
			})
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	}
}

const createActivity = () => {
	submitForm("form")
}

const stopActivity = async () => {
	proxy.$confirm(`此操作将停止【${objectForm.value.title}】规则, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		let params = {
			...objectForm.value,
			status: 3,
		}
		let res = await proxy.$api({ url: config.yx_ds_event_save, data: params });
		if (res.status == 1) {
			proxy.$message({
				message: '停止成功',
				type: 'success'
			});
			emit("addTpBmFun", {
				type: 'del',
				status: 3,
			})
		} else {
			proxy.$message({
				message: res?.msg || '停止失败',
				type: 'error'
			})
		}
	})
}

const goBack = () => {
	emit("backFun", 'back')
}

// 获取详情
const getDetail = async () => {
	sLoading.value = true
	const res = await proxy.$api({ url: config.yx_ds_event_info, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	if (res.status === 1 && res.data) {
		// 将获取到的数据赋值到 objectForm
		const data = res.data
		objectForm.value.id = data.info.id;
		objectForm.value = {
			...objectForm.value,
			...data.info,
			grade: Number(data.info.grade),
			ptype: Number(data.info.ptype),
			v_if: Number(data.info.v_if),
			v_give: Number(data.info.v_give),
			value1: data.info.status == 2 ? true : false,
		}
		console.log("objectForm.value=", objectForm.value)
	}
}

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			form.value?.resetFields()
		}
		if (!newVal) {
			restFun()
		}
	}, 200)
}, { immediate: true })

onMounted(() => { })

// 添加计算属性
const isDisabled = computed(() => {
	const disabledStatus = ["2", "3"]
	return disabledStatus.includes(objectForm.value.status)
})

const handlePriceInput = (value) => {
	objectForm.value.v_if = priceInput(value)
}

const handle2PriceInput = (value) => {
	objectForm.value.v_give = priceInput(value)
}

defineExpose({
	restFun,
	objectForm
})

</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;

			span {
				margin-right: 20px;
			}
		}

		.timeShowBox {
			// width: 600px;
			height: 40px;
			border: 1px solid #DCDFE6;
			border-radius: 5px;
			cursor: pointer;

			.timeShowdiv {
				padding: 0 10px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;

				span {
					margin-right: 10px;

					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}

	::v-deep.mb-box {
		margin-bottom: 10px;

		&:last-child {
			margin: 0;
		}

		.el-radio__label {
			display: none;
		}

		.pl-box {
			font-size: 14px;
			margin-bottom: 10px;
			display: flex;
			align-items: center;
			cursor: pointer;

			span {
				margin-right: 10px;
			}

			img {
				margin-right: 10px;
				width: 25px;
				height: 25px;
			}

			.txt-box {
				width: 145px;
				display: flex;
				align-items: center;
			}
		}

		.color-box {
			display: flex;
			font-size: 14px;

			.color-row {
				margin-right: 10px;
				text-align: center;
				cursor: pointer;

				.color-title {
					font-size: 12px;
					margin: 10px 0;
				}

				.background-item {
					width: 80px;
					height: 80px;
				}
			}
		}
	}
}

.tip-text {
	font-size: 12px;
	color: #666;
	margin-left: 10px;
}



::v-deep .el-color-picker__color {
	border: none !important;
}

::v-deep .el-color-picker__color-inner {
	border: none !important;
}

::v-deep .el-color-picker__mask {
	display: none !important;
}

.ml20 {
	margin-left: 20px;
}

.switch-mode {
	color: #3388ff;
	cursor: pointer;
}

.disabled-btn {
	opacity: 0.5;
	cursor: not-allowed;
	pointer-events: none;
}

.acvite-btn {
	opacity: 1;
	cursor: pointer;
}

::v-deep .el-icon-close:before {
	content: "\e6df";
}

::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
	background-color: #fcfcfc !important;
	color: #666 !important;
	border-color: #f1f1f1 !important;
}

.profit-box {
	margin-left: 20px;
	padding: 20px;
	background-color: #f5f7fa;
	border-radius: 5px;
	img {
		width: 250px;
		height: 130px;
	}
}
</style>